import { defineEventHandler, readBody, setCookie, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import bcrypt from 'bcrypt';

export default defineEventHandler(async (event) => {
  try {
    const { username, password } = await readBody(event);

    if (!username || !password) {
      throw createError({ statusCode: 400, message: '请输入用户名和密码' });
    }

    const db = await getDbConnection();
    const user = await db.get(
      'SELECT id, username, name, password FROM users WHERE username = ?',
      [username]
    );

    if (!user) {
      throw createError({ statusCode: 401, message: '用户名或密码错误' });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw createError({ statusCode: 401, message: '用户名或密码错误' });
    }

    // 创建会话
    const session = {
      userId: user.id,
      username: user.username,
      name: user.name,
      createdAt: new Date().toISOString()
    };

    // 设置会话cookie
    setCookie(event, 'session', JSON.stringify(session), {
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7, // 7天
      sameSite: 'strict',
      path: '/'
    });

    return {
      success: true,
      user: {
        id: user.id,
        username: user.username,
        name: user.name
      }
    };
  } catch (error) {
    console.error('Login error:', error);
    if (error && error.statusCode) {
      throw error;
    }
    throw createError({ statusCode: 500, statusMessage: 'Server error' });
  }
});
